package com.example.androidbrowserpro;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Http {

        //配置默认参数，返回HttpURLConnection的实例
        public String getHttpURLConnection(String info) {
            HttpURLConnection connection=null;
            try {
                URL url = new URL("http://192.168.3.194:9009/v1/errorlog");
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(3000);
                connection.setReadTimeout(3000);
                //设置请求方式 GET / POST 一定要大小
                connection.setRequestMethod("POST");
                connection.setDoInput(true);
                connection.setDoOutput(false);
                connection.connect();
                DataOutputStream dos=new DataOutputStream(connection.getOutputStream());
                String param=info;
                dos.writeBytes(param);
                int responseCode = connection.getResponseCode();
                if (responseCode != 20000) {
                    return responseCode+"";
                }
                String result = getStringByStream(connection.getInputStream());
                System.out.println(result);
            } catch (Exception e) {
                //e.printStackTrace();
                return e.getMessage();
            }
            return "完成";
    }
    private String getStringByStream(InputStream inputStream){
        Reader reader;
        try {
            reader=new InputStreamReader(inputStream,"UTF-8");
            char[] rawBuffer=new char[512];
            StringBuffer buffer=new StringBuffer();
            int length;
            while ((length=reader.read(rawBuffer))!=-1){
                buffer.append(rawBuffer,0,length);
            }
            return buffer.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
